//
//  HDPayoutDetailViewController.swift
//  HuaDaoPeifu
//
//  Created by Erickson on 16/3/29.
//  Copyright © 2016年 paiyipai. All rights reserved.
//

import UIKit
import SDWebImage
import SVProgressHUD
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return l < r
  case (nil, _?):
    return true
  default:
    return false
  }
}

// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func <= <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return l <= r
  default:
    return !(rhs < lhs)
  }
}


class HDPayoutDetailViewController: UIViewController,HDPayOutDetailCellDelegate {

    var canOrNotCommit:Bool = Bool()
    var docTableView: UITableView!
    var applicationBtn:UIButton?
    var selectSection:Int?
    var isShow:String?
    var headerView: HDPayoutHeaderView!
    var footView:HDTimeLineView!
    //保单号
    var policyModel = HDPolicyListModel()
    
    var nameArray = [String]()
    
    var picImageModelArray = [[HDPayoutCaseInitModel]()]
    var imageArray = [[HDUploadImageModel]()]

    var caseId:String!
    var optlogModelArray = [HDPayoutoptLogModel]()
    var casefailModelArray = [HDPayoutCasefailModel]() // 问题列表
    var sunNumber = 0
    var imgNumber = 1

    var imageWhichSection = 0
    var imagewhichUpload = 0
    var haveUploadImage = [Int]()
    var localIssueArray:String = "" // 本地问题列表
    
    var loss_noticeStr = String()
    var pdfName = String()
    var uploadTimeString:Int = 0
    var fuzzyNumber:Int = 0
    
    var  showBigFuzzyNumber:Int = 0
    
    var uploadError:String = ""
    
    var is_dishonorStr:String = ""
    var dishonor_introduceStr:String = ""
    
    var strFee:NSNumber = 0
    
    var bdataTypeNumberArray = [Int]()

    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        NotificationCenter.default.post(name: Notification.Name(rawValue: "BACKFROMDETAIL"), object: nil)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        print("viewWillAppear")
        fuzzyNumber = fuzzyNumber + showBigFuzzyNumber
        if (docTableView != nil) {
            headerView.removeFromSuperview()
            headerView = nil
            headerView = HDPayoutHeaderView()
            headerView.payoutStatus = self.policyModel.status
            headerView.casefailModelArray = self.casefailModelArray
            headerView.localIssueNumber = "\(fuzzyNumber)"
            headerView.is_dishonorStr = self.is_dishonorStr
            headerView.dishonor_introduceStr = self.dishonor_introduceStr
            headerView.delegate = self
            headerView.showBtn.setTitle("", for: UIControlState())
            headerView.showMoney = self.strFee
            headerView.setupHeaderView()
            let headerViewHeight = headerView.backViewHeight()
            
            headerView.frame = CGRect(x: 0, y: 0, width: AppConstant.screenWidth, height: headerViewHeight)
            
            docTableView.tableHeaderView = headerView
            docTableView.reloadData()
        }
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        requestModel()
        canOrNotCommit = true
        setupNavigation()
        if (self.policyModel.status == "-1" || self.policyModel.status == "0" || self.policyModel.status == "2" || self.policyModel.status == "5"||self.policyModel.status == "7"){
            setupApplication()
        }
        
    }
    
    
    func setupTableView() {
        if docTableView != nil {
            docTableView.snp.removeConstraints()
        }else{
            docTableView = UITableView()
            self.view.addSubview(docTableView)
            if self.policyModel.status == "0"||self.policyModel.status == "-1" {
                isShow = "show"
            }else{
                isShow = "notShow"

            }
        }
        if (self.policyModel.status == "-1" || self.policyModel.status == "0" || self.policyModel.status == "2" || self.policyModel.status == "5" || self.policyModel.status == "7"){

            docTableView.snp.makeConstraints { (make) in
                make.edges.equalTo(self.view).inset(UIEdgeInsetsMake(0, 0, 48, 0))
            }
        }else{
            docTableView.snp.makeConstraints { (make) in
                make.edges.equalTo(self.view).inset(UIEdgeInsetsMake(0, 0, 0, 0))
            }
            
            if (applicationBtn != nil) {
                applicationBtn!.snp.removeConstraints()
            }

        }
        docTableView.dataSource = self
        docTableView.delegate = self
        docTableView.separatorStyle = .none
        docTableView.reloadData()
        
        headerView = HDPayoutHeaderView()
        headerView.payoutStatus = self.policyModel.status
        headerView.casefailModelArray = self.casefailModelArray
        if self.policyModel.status == "-1"||self.policyModel.status == "0"||self.policyModel.status == "2"||self.policyModel.status == "5" {
            headerView.localIssueNumber = "\(fuzzyNumber)"

        }else{
            headerView.localIssueNumber = "0"

        }
        headerView.is_dishonorStr = self.is_dishonorStr
        headerView.dishonor_introduceStr = self.dishonor_introduceStr
        headerView.delegate = self
        headerView.showBtn.setTitle("", for: UIControlState())
        headerView.showMoney = self.strFee
        headerView.setupHeaderView()
        let headerViewHeight = headerView.backViewHeight()

        headerView.frame = CGRect(x: 0, y: 0, width: AppConstant.screenWidth, height: headerViewHeight)

        docTableView.tableHeaderView = headerView
        footView = HDTimeLineView()
        footView.timeArray = self.optlogModelArray
        footView.uploadTimeStr = uploadTimeString
        footView.status = self.policyModel.status
        footView.setupTimeLineView()
        docTableView.tableFooterView = footView
        
        if self.policyModel.status == "0"||self.policyModel.status == "-1" {
            if isShow == "show"{
                headerView.showBtn.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI))
                headerView.showBtn.isSelected = true
                
            }
        }
        

    }
    
    func requestModel(){
        SVProgressHUD.showDisableLoading(nil)

        HDApiManagerHandler.requestCaseInit(self.policyModel.policyno, success: { [unowned self](response) in
            print(response)
            SVProgressHUD.dismiss()
            if response["status"]?.int32Value == 1{
                let  dict:NSDictionary = response["data"] as! NSDictionary
//                self.policyModel.status = dict["status"] as! String
//                print("=============\(self.policyModel.status)")
                self.caseId = dict["case_id"] as! String
                self.picGetWith(dict["datatype_list"] as! NSDictionary)
                
                self.is_dishonorStr = dict["is_dishonor"] as! String
                
                if self.is_dishonorStr != "1" {
                    self.dishonor_introduceStr = dict["dishonor_introduce"] as! String
                }
                
                print("------\(self.strFee)")
                
                self.optlogGet(dict)
                
                
                //最近更新时间
                self.uploadTimeString = Int((dict["updated"] as? String)!)!
                //问题列表
                self.casefailData(dict)
                ////////
                //
                
                if self.policyModel.status != "-1"{
                    self.lossNotice(dict)
                }
                if (self.policyModel.status == "-1" || self.policyModel.status == "0" || self.policyModel.status == "2" || self.policyModel.status == "5"){

                    self.isCanCommit()

                }
                
                if (self.policyModel.status == "-1" || self.policyModel.status == "0" ){
                    self.strFee =  dict["maxfee"] as! NSNumber

                }else{
                    self.strFee =  dict["fee"] as! NSNumber

                }
                self.setupTableView()

            }
            }) { (error) in
                print(error)
        }
    }
    
    //获取图片
    func picGetWith(_ dict:NSDictionary){
        if self.picImageModelArray.count > 0 {
            self.picImageModelArray.removeAll()
        }
        if self.imageArray.count > 0{
            self.imageArray.removeAll()
            
        }
        var getArray = [HDUploadImageModel]()

        for index in 0 ..< self.nameArray.count{

            let str = self.nameArray[index]
            let dataArr = dict[str] as! NSArray
            let  modelArray = HDPayoutCaseInitModel.parses(dataArr) as! [HDPayoutCaseInitModel]
            self.picImageModelArray.append(modelArray)
            
            haveUploadImage.append(modelArray.count)
            //仅仅为了初始化相同空间的数组，接收从相册或者拍照过来的数据
            self.imageArray.append(getArray)
        }
        
        for index in 0 ..< self.nameArray.count {
            for numberImage in 0..<self.picImageModelArray[index].count {
                
                let image = HDSaveImage.imageWithMessage(self.caseId, dataType: self.nameArray[index], imageCount: numberImage)
                let model = HDUploadImageModel()
                model.image = image as? UIImage
                model.imageStatus = .clear
                self.imageArray[index].append(model)
            }
            
        }
        
        if (self.policyModel.status == "-1" || self.policyModel.status == "0" || self.policyModel.status == "5" || self.policyModel.status == "2"){
            //取本地存储图片
            for index in 0..<self.nameArray.count {
                let back = HDSaveImage.getPictureWith(caseId, dataType: self.nameArray[index])
                if back != nil {
                    let saveImageArray = back as! [HDPayoutSaveImageModel]
                    for indexSave in 0..<saveImageArray.count {
                        let model = HDPayoutCaseInitModel ()
                        let imageModel = HDUploadImageModel()
                        imageModel.image = saveImageArray[indexSave].notUploadImage
                        model.notUploadImage =  saveImageArray[indexSave].notUploadImage
                        if saveImageArray[indexSave].imageStatus.int32Value == 1 {
                            model.imageStatus = .clear
                            imageModel.imageStatus = .clear
                        }else{
                            imageModel.imageStatus = .fuzzy
                            model.imageStatus = .fuzzy
                            fuzzyNumber += 1
                        }
                        getArray.append(imageModel)
                        self.picImageModelArray[index].append(model)
                        self.imageArray[index].append(imageModel)
                    }
                    
                }
                
            }
        }

    }
    
    func optlogGet(_ dict:NSDictionary){
        let dataArr = dict["optlog"] as! NSArray
        self.optlogModelArray = HDPayoutoptLogModel.parses(dataArr) as! [HDPayoutoptLogModel]
    }
    
    // 错误信息列表
    func casefailData(_ dict:NSDictionary){
        let dataArr = dict["casefail"] as! NSArray
        self.casefailModelArray = HDPayoutCasefailModel.parses(dataArr) as! [HDPayoutCasefailModel]
        
    }
    // 获取预赔案通知书
    func lossNotice(_ dict:NSDictionary){
        loss_noticeStr = dict["loss_notice"] as! String
        if loss_noticeStr.characters.count>0 {
            let lossArray = loss_noticeStr.components(separatedBy: "/")
            pdfName = lossArray.last!
            let filePath = FileManager.default
            let pdfPath =   AppConstant.documentsPath + "/" + pdfName
            print(filePath.fileExists(atPath: pdfPath))
            if !filePath.fileExists(atPath: pdfPath){
                DispatchQueue.global(priority: .background).async(execute: {
                    
                    HDApiManagerHandler.requestDownloadNotice(self.loss_noticeStr)
                    
                })
            }
            
        }
    }
    
    func requestUploadImage(_ uploadImage:UIImage,dataType:Int,imgnumber:Int,totalNumber:Int){

        SVProgressHUD.showDisableLoading("\(self.imgNumber)/\(self.sunNumber)")
        
        let repModel = HDCaseUploadRepModel()
        repModel.policyno = self.policyModel.policyno
        repModel.datatype = self.nameArray[dataType]
        repModel.case_id = self.caseId
        repModel.imgnumber = String(imgnumber)
        repModel.imgtotal = String(totalNumber)
        repModel.img = uploadImage
        HDApiManagerHandler.requestCaseUpload(repModel, success: {[unowned self] (response) in
            
            if response["status"]?.int32Value == 1{
                
                let haveuploadNumber = self.haveUploadImage[self.imageWhichSection] + 1
                self.haveUploadImage[self.imageWhichSection] = haveuploadNumber
                
                
                let pictureNumber:Int = self.picImageModelArray[self.imageWhichSection].count - 1
                var saveImageArray = [HDPayoutCaseInitModel]()
                
                if(self.picImageModelArray[self.imageWhichSection].count - 1 == pictureNumber){
                     HDSaveImage.removeSaveFile(self.caseId, dataType: self.nameArray[self.imageWhichSection])
                }else{
                    saveImageArray.append(contentsOf: self.picImageModelArray[self.imageWhichSection][self.imagewhichUpload...pictureNumber])
                    self.saveImageWith(saveImageArray)
                }
                
                HDSaveImage.saveImageWithImageName(uploadImage, caseId: self.caseId, dataType: self.nameArray[dataType], imageCount: self.imagewhichUpload)
                
                if self.imgNumber == self.sunNumber {
                    SVProgressHUD.showSuccess("上传成功")
                    self.fuzzyNumber = 0
                    self.requestModel()
                    self.policyModel.status = "1"
                    NotificationCenter.default.post(name: Notification.Name(rawValue: "UPLOADEDALLIMAGE"), object: nil)
                    for index in 0..<self.picImageModelArray.count{
                        self.haveUploadImage[index] = self.picImageModelArray[index].count
                    }
                    
                    for removeImdex in 0..<self.nameArray.count{
                        HDSaveImage.removeSaveFile(self.caseId, dataType: self.nameArray[removeImdex])
                    }
                }
                
                
                self.imgNumber += 1
                self.imagewhichUpload += 1
                self.judgmentUploadImage()
                
                

            }else{
                //上传失败时，保存本地的数据天假失败icon
                self.uploadError = "error"
                SVProgressHUD.dismiss()
                self.docTableView.reloadData()
                
            }
     
            
            
            
            }) { (failure) in
                //上传失败时，保存本地的数据天假失败icon
                self.uploadError = "error"
                SVProgressHUD.dismiss()
                self.docTableView.reloadData()

        }
    }
    
    func judgmentUploadImage(){
        
        if self.imageWhichSection < self.nameArray.count{
            if self.imagewhichUpload < self.imageArray[self.imageWhichSection].count{
                if self.imageArray[self.imageWhichSection].count > self.haveUploadImage[self.imageWhichSection] {
                    let model = self.imageArray[self.imageWhichSection][self.imagewhichUpload]
                    
                    self.requestUploadImage(model.image!, dataType: self.imageWhichSection, imgnumber: self.imgNumber, totalNumber: self.sunNumber)
                }else{
                    self.imageWhichSection += 1
                    if self.imageWhichSection < self.nameArray.count {
                        self.imagewhichUpload = self.haveUploadImage[self.imageWhichSection]
                        judgmentUploadImage()
                    }
                }
                
            }else{
                self.imageWhichSection += 1
                if self.imageWhichSection < self.nameArray.count {
                    self.imagewhichUpload = self.haveUploadImage[self.imageWhichSection]
                    judgmentUploadImage()
                }
            }
            
        }
        
    }
    
    
    func setupNavigation() {
        title = "赔付状态"
        let rightItem = UIBarButtonItem(title: "产品详情", style: .plain, target: self, action: #selector(rightItemAction))
        navigationItem.rightBarButtonItem = rightItem
    }
    
    func setupApplication(){
         applicationBtn = UIButton()
        self.view.addSubview(applicationBtn!)
        applicationBtn!.snp.makeConstraints { (make) in
            make.bottom.equalTo(0)
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.height.equalTo(48)
        }

        applicationBtn?.titleLabel?.font = UIFont.systemFont(ofSize: 18)
        if self.policyModel.status == "7"{
            applicationBtn!.setTitle("重新提交", for: UIControlState())

        }else{
            applicationBtn!.setTitle("提交申请", for: UIControlState())

        }
        if canOrNotCommit {
            applicationBtn!.backgroundColor = ConstantColor.appThemeColor
            applicationBtn!.isUserInteractionEnabled = true
        }else{
            applicationBtn!.backgroundColor = UIColor(hex:0xcccccc)
            applicationBtn?.isUserInteractionEnabled = false
        }
        applicationBtn?.addTarget(self, action: #selector(HDPayoutDetailViewController.commitApplication), for: .touchUpInside)
    }
    /// 计算是否可以点击提交
    func isCanCommit(){
        let zeroArray = NSMutableArray()
        
        var numberOfShoudAddimage:Int = 0
        if self.policyModel.status == "2"||self.policyModel.status == "5" {
            numberOfShoudAddimage = self.casefailModelArray.count
            for index in 0..<self.casefailModelArray.count {
                let str = self.casefailModelArray[index].datatype
                
                for indexStr in 0..<self.nameArray.count{
                    if str == self.nameArray[indexStr] {
                        let number = picImageModelArray[indexStr].count - haveUploadImage[indexStr]
                        if number == 0 {
                            zeroArray.insert(0, at: index)
                        }else{
                            zeroArray.insert(1, at: index)
                        }
                    }
                }
            }
            
        }else{
            numberOfShoudAddimage = bdataTypeNumberArray.count
            for index in 0..<bdataTypeNumberArray.count{
                let addImageIndex = bdataTypeNumberArray[index]
                let number = picImageModelArray[addImageIndex].count
                if number == 0 {
                    zeroArray.insert(0, at: index)
                }else{
                    zeroArray.insert(1, at: index)
                }
            }
        }
        
        var sum:Int = 0
        for arrayNumber in zeroArray{
            sum += arrayNumber as! Int
        }
        if sum < numberOfShoudAddimage {
            canOrNotCommit = false
            applicationBtn!.backgroundColor = UIColor(hex:0xcccccc)
            applicationBtn?.isUserInteractionEnabled = false
        }else{
            canOrNotCommit = true
            applicationBtn!.backgroundColor = ConstantColor.appThemeColor
            applicationBtn!.isUserInteractionEnabled = true
        }
        
        if self.policyModel.status == "7"{
            canOrNotCommit = true
            applicationBtn!.backgroundColor = ConstantColor.appThemeColor
            applicationBtn!.isUserInteractionEnabled = true
            
        }
        
    }
    
    func commitApplication(){
        
        if self.policyModel.status == "7"{
            
            resubmitRequest()
            return
            
        }
        if self.policyModel.status != "2" && self.policyModel.status != "5"{
            let freeNumber = headerView.moneyView.moneyTextField.text?.floatValue
            if freeNumber <= 0 {
                SVProgressHUD.showError("请填写此次申请理赔金额")
                return
            }
        }
        
        
        for number in 0..<self.nameArray.count {
            sunNumber += self.imageArray[number].count - haveUploadImage[number]
        }
        
        canOrNotCommit = false
        applicationBtn!.backgroundColor = UIColor(hex:0xcccccc)
        applicationBtn?.isUserInteractionEnabled = false
        
        //-----------------
        requestMoney()


        for index in 0..<self.nameArray.count {
            if self.imageArray[index].count>0 && (self.imageArray[index].count > self.haveUploadImage[index]) {
                self.imageWhichSection = index
                    imagewhichUpload = self.haveUploadImage[index]
                    let model = self.imageArray[index][imagewhichUpload]
                    self.requestUploadImage(model.image!, dataType: index, imgnumber: self.imgNumber,totalNumber: self.sunNumber)
                    break
            }
            
        }
    }
    // MARK: - rightItemAction
    func rightItemAction() {
        let insurance = HDInsuranceViewController()
        insurance.policynoStr = "&policyno=" + self.policyModel.policyno
        navigationController?.pushViewController(insurance, animated: true)
    }
    
    func addImageClickDelegate(_ sender:HDImageBtn){
        
        let contr = HDTakePhotoViewController()
        contr.delegate = self
        contr.takeType = .take
        selectSection = sender.selectIndexPath
        let nav = BaseNavigationController.init(rootViewController: contr)
        self.present(nav, animated: true, completion: nil)
    }
    
    func showBigImageClickDelegate(_ sender: HDImageBtn) {
        
        
        let contr = HDImageBrowserViewController()
        let model = HDUploadDetailImageModel()
        model.currentIndex = sender.selectImageNumber
        model.IndexOfNewImage = self.haveUploadImage[sender.selectIndexPath]
        let statusValue = Int(self.policyModel.status)
        model.status = NSNumber(value:statusValue!)
        model.uploadImags = self.picImageModelArray[sender.selectIndexPath]
        contr.imageDetail = model
        contr.delegate = self
        selectSection = sender.selectIndexPath

        navigationController?.pushViewController(contr, animated: true)
        
    }
    
    deinit{
        print("deinit")
    }
    
}

// MARK: - UITableViewDataSource
extension HDPayoutDetailViewController: UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.picImageModelArray.count
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return  1
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let detailModel = HDPayoutDetailModel()
        detailModel.imageArray = self.picImageModelArray[indexPath.section]
        detailModel.nameArray = self.nameArray
        detailModel.caseid = self.caseId
        detailModel.uploadImageArray = self.imageArray[indexPath.section]
        detailModel.status = self.policyModel.status
        detailModel.casefailModelArray = casefailModelArray
        detailModel.isShow = isShow!
        detailModel.indexPath = indexPath
        detailModel.uploadError = self.uploadError
        detailModel.haveUploadImageInter = haveUploadImage[indexPath.section]
        var  cellStr = "payout" + String(indexPath.section)
        cellStr += isShow! + self.policyModel.status
        var cell = tableView.dequeueReusableCell(withIdentifier: cellStr) as? HDPayoutDetailTableViewCell
        if cell == nil {
            cell = HDPayoutDetailTableViewCell(style: .default, reuseIdentifier: cellStr)

        }
        cell?.payDetailModel = detailModel
        cell!.delegate = self
        cell!.selectionStyle = .none

        
        return cell!
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if isShow == "notShow" {
            return 0
        }
        
        var integerNumber = 0
        let modelArray = self.picImageModelArray[indexPath.section]

        if self.policyModel.status == "1" {
            integerNumber = 0
            
        }else{
            if self.picImageModelArray[indexPath.section].count - haveUploadImage[indexPath.section]<10 {
                if self.policyModel.status == "0"||self.policyModel.status == "-1" {
                    integerNumber = 1
                }else{
                    for index in 0..<self.casefailModelArray.count {
                        let str = self.casefailModelArray[index].datatype
                        if str == nameArray[indexPath.section] {
                            integerNumber = 1
                        }
                    }
                }
                
            }else{
                integerNumber = 0
            }
            
        }
        
        let numberImage = modelArray.count +  integerNumber
        let imageHeightOrWith = Int(AppConstant.screenWidth - 20*5 - 14)/4

        if numberImage/4 == 0 {
            return CGFloat(imageHeightOrWith + 15) + 10
        }else{
            if numberImage%4 > 0 {
                return CGFloat((imageHeightOrWith + 15)*(numberImage/4 + 1))
            }
            return CGFloat((imageHeightOrWith + 15)*(numberImage/4))

        }
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        headerView.moneyView.moneyTextField.resignFirstResponder()
        let sectionHeaderHeight:CGFloat = 44;
        if((scrollView.contentOffset.y >= 0)&&(sectionHeaderHeight >= scrollView.contentOffset.y)){
            scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0)
        }else if(scrollView.contentOffset.y>=sectionHeaderHeight){
            scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0)
        }
    }
}

// MARK: - UITableViewDelegate
extension HDPayoutDetailViewController : UITableViewDelegate {
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if isShow == "notShow" {
            return 0
        }
        return 44
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let headerView = HDPayoutSectionHeaderView()
        headerView.frame = CGRect(x: 0,y: 0,width: AppConstant.screenWidth,height: 44)
        headerView.section = section
        headerView.nameArray = self.nameArray
        headerView.statusStr = self.policyModel.status
        headerView.casefailModelArray = self.casefailModelArray
        headerView.bdatatypeArray = self.bdataTypeNumberArray
        headerView.setupView()

        return headerView
    }
    
}


extension HDPayoutDetailViewController:HDheaderViewDelegate{
    func headerViewBtnClick(){
        if isShow == "notShow"{
            isShow = "show"
            headerView.showBtn.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI))
            
        }else{
            isShow = "notShow"
            headerView.showBtn.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI*2))
            
            
        }
        docTableView.reloadData()
    }
    
    func noticeImageClick() {
        if pdfName.characters.count > 0 {
            let filePath = FileManager.default
            let pdfPath =   AppConstant.documentsPath + "/" + pdfName
            print(filePath.fileExists(atPath: pdfPath))
            if filePath.fileExists(atPath: pdfPath) {
                let document = ReaderDocument.withDocumentFilePath(pdfPath, password: nil)
                if(document != nil){
                    let contr = ReaderViewController.init(readerDocument: document)
                    self.navigationController?.pushViewController(contr!, animated: true)
                    
                }
            }else{
                navigationController?.pushViewController(HDNoticeNUllViewController(), animated: true)
            }

        }else{
            navigationController?.pushViewController(HDNoticeNUllViewController(), animated: true)

        }
        
        
    }
    
    
    func saveImageWith(_ image: [HDPayoutCaseInitModel]){
        
        var saveImageArray = [HDPayoutSaveImageModel]()
        for index in 0..<image.count {
            
            let saveModel = HDPayoutSaveImageModel()
            saveModel.notUploadImage = image[index].notUploadImage
            saveModel.imageStatus = 1
            if image[index].imageStatus == .fuzzy {
                saveModel.imageStatus = 2
            }
            saveImageArray.append(saveModel)
        }
        
        HDSaveImage.savePictureWith(saveImageArray, caseId: caseId, dataType: self.nameArray[selectSection!])
    }
}
// 跳转拍照
extension HDPayoutDetailViewController:HDTakePhotoViewControllerDelegate{
    func numberOfPhotosNeedToUpload() -> Int {
        
        let number = self.picImageModelArray[selectSection!].count - self.haveUploadImage[selectSection!]
        return (10 - number)
    }
    
    func didFinishedPickPhotos(_ images: [HDUploadImageModel]) {
        print(images.count)
        self.imageArray[selectSection!].append(contentsOf: images)
        print("hahahha")
        
        
        for index in 0..<images.count {
            let model = HDPayoutCaseInitModel()
            model.dt_id = "0"
            model.imageStatus = images[index].imageStatus!
            model.notUploadImage = images[index].image
            (self.picImageModelArray[selectSection!]).append(model)
        }
        

    }
    
    func didFinishedTakePhotos(_ image: [HDPayoutCaseInitModel]) {
        print("didFinishedTakePhotos--->:\(image.count)")
        
        showBigFuzzyNumber = 0
        for index in 0..<self.picImageModelArray[selectSection!].count {
            let picModel = self.picImageModelArray[selectSection!][index]
            if picModel.imageStatus == .fuzzy {
                showBigFuzzyNumber -= 1
            }
        }

        
        self.picImageModelArray[selectSection!].append(contentsOf: image)
    
        
        
        for index in 0..<image.count {
            let model = HDUploadImageModel()
            model.imageStatus = image[index].imageStatus
            model.image = image[index].notUploadImage
            self.imageArray[selectSection!].append(model)
            
        }
        
        var saveArray:[HDPayoutCaseInitModel] = [HDPayoutCaseInitModel]()
            saveArray.append(contentsOf: self.picImageModelArray[selectSection!][haveUploadImage[selectSection!]...self.picImageModelArray[selectSection!].count-1])
        
        for index in 0..<saveArray.count {
            let picModel = saveArray[index]
            if picModel.imageStatus == .fuzzy {
                showBigFuzzyNumber += 1
            }
        }
        
        saveImageWith(saveArray)
        
        if (self.policyModel.status == "-1" || self.policyModel.status == "0" || self.policyModel.status == "2" || self.policyModel.status == "5"){
            
            isCanCommit()
        }
        self.docTableView.reloadData()
    }
}


//从查看大图返回
extension HDPayoutDetailViewController:HDImageBrowserViewControllerDelegate{
    func didFinishedRetakePhoto(_ imageDetail: HDUploadDetailImageModel) {
        
//        print("tttttt返回：\(imageDetail.uploadImags.count)")
//        showBigFuzzyNumber = 0
//        for index in 0..<self.picImageModelArray[selectSection!].count {
//            let picModel = self.picImageModelArray[selectSection!][index]
//            if picModel.imageStatus == .Fuzzy {
//                showBigFuzzyNumber -= 1
//            }
//        }
//        
//        for index in 0..<imageDetail.uploadImags.count {
//            let picModel = imageDetail.uploadImags[index]
//            if picModel.imageStatus == .Fuzzy {
//                showBigFuzzyNumber += 1
//            }
//        }


        self.picImageModelArray[selectSection!] = imageDetail.uploadImags
        
        fuzzyNumber = 0
        showBigFuzzyNumber = 0
        for index in 0..<self.picImageModelArray.count {
            
            for indexFuzzy in 0..<self.picImageModelArray[index].count {
                let picModel = self.picImageModelArray[index][indexFuzzy]
                if picModel.imageStatus == .fuzzy {
                        fuzzyNumber += 1
                            }
            }
        }
        
        var backImageArr = [HDUploadImageModel]()
        var saveImageArray = [HDPayoutCaseInitModel]()
        for index in self.haveUploadImage[selectSection!]..<self.picImageModelArray[selectSection!].count{
            var saveModel = HDPayoutCaseInitModel()
            let model = HDUploadImageModel()
            model.image = imageDetail.uploadImags[index].notUploadImage
            model.imageStatus = imageDetail.uploadImags[index].imageStatus
            backImageArr.append(model)
            
            saveModel = imageDetail.uploadImags[index]
            saveImageArray.append(saveModel)
        }
        saveImageWith(saveImageArray)

        if backImageArr.count >= 1 {
            for _ in 0..<self.picImageModelArray[selectSection!].count - imageDetail.IndexOfNewImage! + 1{
                
                self.imageArray[self.selectSection!].removeLast()
                
                
            }
            self.imageArray[self.selectSection!].append(contentsOf: backImageArr[0...backImageArr.count - 1])
        }else{
            self.imageArray[self.selectSection!].removeLast()
        }
        
        if (self.policyModel.status == "-1" || self.policyModel.status == "0" || self.policyModel.status == "2" || self.policyModel.status == "5"){
            
            isCanCommit()
        }

        
        docTableView.reloadData()
        
    }
}

extension HDPayoutDetailViewController{
    
    
    func requestMoney(){
        print(headerView.moneyView.moneyTextField.text ?? "空的", self.strFee)
        var  freeNumber:String = String()
         if (self.policyModel.status == "2" || self.policyModel.status == "5"){
            freeNumber = String(format: "%.2f",self.strFee.floatValue)
         }else{
            if let a = headerView.moneyView.moneyTextField.text?.floatValue{
                freeNumber = String(format: "%.2f",a)
            }
        }
        
        HDApiManagerHandler.requestCaseLoan(self.caseId, hopeFee:freeNumber , success: { (response) in
            print("--------")
        }) { (failure) in
            print("----------")
        }
        
    }
    
    
    func resubmitRequest(){
        
        HDApiManagerHandler.requestResubMit(self.caseId, success: { (response) in
            print("-----\(response)-----")
            if response["status"]!.int32Value == 1{
                self.navigationController!.popViewController(animated: true)
            }
            
            }) { (error) in
                print("-----------")
        }
        
    }
    
    
    
}


